package cn.edu.scau.jds.dao;

import cn.edu.scau.jds.entity.BaseEntity;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

/**
 * Created by junbin(seraphstorm@163.com) on 2016-01-26.
 */
@SuppressWarnings(value = {"unchecked"})
public class BaseDao<T extends BaseEntity> extends SqlSessionDaoSupport {

    private final Class<?> actualClazz;

    {
        actualClazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    /**
     * 根据方法id名称生成mapper文件的绝对定位
     *
     * @param methodName 方法的id
     * @return 该方法的绝对定位
     */
    protected String getMethodPath(String methodName) {
        return actualClazz.getName() + "." + methodName;
    }

    public void add(T t) {
        this.getSqlSession().insert(getMethodPath("add"), t);
    }

    public void delete(long id) {
        this.getSqlSession().delete(getMethodPath("delete"), id);
    }

    public void update(T t) {
        this.getSqlSession().update(getMethodPath("update"), t);
    }

    public T load(long id) {
        return this.getSqlSession().selectOne(getMethodPath("load"), id);
    }

    public boolean isExists(T t) {
        Integer result = this.getSqlSession().selectOne(getMethodPath("exists"), t.getId());
        return !(result == null || result == 0) && result == 1;
    }
}
